
package com.probiz.estoresf.customer.web.action;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.probiz.estore.Constants;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.content.NewsletterGroup;
import com.probiz.estore.common.model.content.Subscriber;
import com.probiz.estore.common.model.system.AppUser;
import com.probiz.estore.content.service.NewsletterGroupManager;
import com.probiz.estore.content.service.SubscriberManager;
import com.probiz.estore.core.controller.GenericStoreFrontController;
import com.probiz.estore.webapp.util.RequestContext;

public class NewsSubscriptionController extends
		GenericStoreFrontController<Subscriber> {
	private SubscriberManager		subscriberManager;
	private NewsletterGroupManager	newsletterGroupManager;

	@Override
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		String emailParam = "email";
		if (logger.isDebugEnabled()) {
			logger
					.debug("entering 'NewsSubscriptionController defaultAction' method");
		}

		String email = request.getParameter(emailParam);
		boolean isAnonymusUser = RequestContext.isAnonymousUser();
		if (isAnonymusUser && !ConfigUtil.getInstance().getIsAnonymousNewsSubscriptionEnabled()) {
			//要求登录
			return new ModelAndView("redirect:/login.html?"+Constants.SAVED_URL_KEY+"="+ConfigUtil.getInstance().getStoreFrontSiteUrl()+"/customer/newsSubscription.html");
		} else {
			AppUser appUser = RequestContext.getCurrentUser();
			if(appUser!=null){
				email = appUser.getEmail();				
			}
		}
		List<NewsletterGroup> newsletterGroupList = loadAllletterGroupAndInit(
				request, email);
		request.setAttribute(emailParam, email);
		return new ModelAndView("customer/newsSubscription",
				"newsletterGroupList", newsletterGroupList);
	}

	/**
	 * 载入所有可用的消息组,如果当前某项消息组已给当前用户订阅，则当前消息组check==true;
	 * 
	 * @param request
	 * @param email
	 * @return
	 */
	private List<NewsletterGroup> loadAllletterGroupAndInit(
			HttpServletRequest request, String email) {
		// 获取所有消息组;
		List<NewsletterGroup> newsletterGroupList = newsletterGroupManager
				.getAllActiveNewsletterGroupList();
		// 获取已订阅消息组
		List<Integer> subscribedNewsletterGroupIdList = subscriberManager
				.getSubscribedNewsletterGroupIdsByEmail(email);
		request.setAttribute("subscribedNewsletterGroupIdList",
				subscribedNewsletterGroupIdList);
		if (newsletterGroupList != null
				&& subscribedNewsletterGroupIdList != null) {
			for (NewsletterGroup newsGroup : newsletterGroupList) {
				for (Integer id : subscribedNewsletterGroupIdList) {
					if (newsGroup.getNewsletterGroupId().intValue() == id
							.intValue()) {
						newsGroup.setChecked(true);
					}
				}
			}
		}
		return newsletterGroupList;
	}
	public ModelAndView subscribe(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		String email = request.getParameter("subscribe_email");
		String[] newsletterGroupIds = request.getParameterValues("newsletterGroupId");
		if(ArrayUtils.isEmpty(newsletterGroupIds)){
			saveErrorMessage(request, getMessage("newsSubscription.failSubscription"));
		}else{
			for (String letterGroup : newsletterGroupIds) {
				subscriberManager.addSubscriber(email,new Integer(letterGroup));
			}
			saveMessage(request, getMessage("newsSubscription.finishSubscription", new Object[] { email }));
		}
		return new ModelAndView(new RedirectView("newsSubscription.html?email=" + email));
	}
	
	public ModelAndView cancelSubscribe(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		String email = request.getParameter("unsubscribe_email");
		if(subscriberManager.isSubscriberExist(email)){
			subscriberManager.removeAllSubscriptions(email);
			saveMessage(request, getMessage("newsSubscription.cancelSubscription", new Object[] { email }));
		}else{
			saveErrorMessage(request, getMessage("newsSubscription.failUnsubscription", new Object[] { email }));
		}
		return new ModelAndView(new RedirectView("newsSubscription.html?email=" + email));
	}
	

	@Override
	protected void initController() throws Exception {
		mgr = subscriberManager;
	}

	public void setSubscriberManager(SubscriberManager subscriberManager) {
		this.subscriberManager = subscriberManager;
	}

	public void setNewsletterGroupManager(
			NewsletterGroupManager newsletterGroupManager) {
		this.newsletterGroupManager = newsletterGroupManager;
	}

}